/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // void dfs(TreeNode* root, string nums, int& ret)
    // {
    //     if (root == nullptr)
    //         return;

    //     nums += to_string(root->val);

    //     if (root->left == nullptr && root->right == nullptr)
    //     {
    //         ret += stoi(nums);
    //         return;
    //     }

    //     dfs(root->left, nums, ret);
    //     dfs(root->right, nums, ret);
    // }
    // int sumNumbers(TreeNode* root) {
    //     int ret = 0;
    //     string nums;
    //     dfs(root, nums, ret);

    //     return ret;
    // }

    int sumNumbers(TreeNode* root, int prevsum = 0) {
        if (root == nullptr)
            return 0;

        prevsum = prevsum * 10 + root->val;
        if (root->left == nullptr && root->right == nullptr)
            return prevsum;

        return sumNumbers(root->left, prevsum) + sumNumbers(root->right, prevsum);
    }
};
   
   

